/*
  This file is part of JCM.

  JCM is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  JCM is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with JCM.  If not, see <http://www.gnu.org/licenses/>.
*/
import javax.swing.JProgressBar;

/**
 * Gerenciador de componente JProgressBar em execução concorrente.
*/
public class Temporizador extends Thread
{
  /** O progress bar a gerenciar. */
  private JProgressBar bar;

  /** Amplitude numérica do progress bar. */
  private int range;

  /** Valor mínimo do progress bar. */
  private int barMinimum;

  /** Valor máximo do progress bar. */
  private int barMaximum;

  /** Posição de preenchimento do progress bar num instante qualquer. */
  private int position;

  /** Indicador lógico de preenchimento completado. */
  private boolean stop;

  /** Atualiza o canvas da interface visual do progress bar. */
  private void updateUI()
  {
    bar.getUI().update(bar.getGraphics(), bar);
  }

  /**
   * Construtor do objeto.
   *
   * @param bar O componente JProgressBar a gerenciar.
  */
  public Temporizador(JProgressBar bar)
  {
    this.bar = bar;
    position = barMinimum = bar.getMinimum();
    barMaximum = bar.getMaximum();
    range = barMaximum - barMinimum;
    stop = false;
  }

  /**
   * Atualiza o progress bar com o valor fornecido.
   *
   * @param percent O novo valor do progress bar.
  */
  public void update(double percent)
  {
    if (! bar.isIndeterminate())
      position = (int) Math.round(percent * range) + barMinimum;
  }

  /**
   * Atualiza o progress bar enquanto não preenchido por completo
   * então exibe um texto de aviso até que o gerenciamento seja
   * encerrado.
  */
  @Override public void run()
  {
    while (! stop) {
      try
      {
        if (! bar.isIndeterminate())
        {
          bar.setValue(position);
          if (stop = (position == barMaximum)) bar.setStringPainted(true);
        }
        updateUI();
        sleep(75);

      } catch (InterruptedException e) {
        System.err.println(e);
      }
    }
  }

  /** Encerra o gerenciamento voltando ao estado inicial. */
  public void terminate()
  {
    stop = true;
    bar.setStringPainted(false);
    bar.setValue(barMinimum);
  }
}
